#-*-coding:utf-8-*-

import yunpian
import dante
import logging
import json
import datetime
from dante.database import db_session, Sms
from dante.util import Result

logger = logging.getLogger('Dante')

def retrieve_and_send(msgid):
	APIKEY = dante.app.config['API_KEY']
	sms = Sms.query.filter(Sms.id == msgid).first()
	logger.info('Sending message id = [{0}]'.format(sms.id))
	result_str = yunpian.send_sms(APIKEY, sms.content, sms.mobile)
	result = json.loads(result_str)
	logger.info('Sending message complete, get response from Yunpian: [{0}]'.format(result))
	status = Sms.ERROR
	if result['code'] == 0:
		status = Sms.SUCCESS
	Sms.query.filter(Sms.id == sms.id).update({Sms.status: status, Sms.yunpian_result: result_str, Sms.send_time: datetime.datetime.now()})
	db_session.commit()

def add_to_schedule_queue(msgid):
	logger.info('Scheduled message [{0}] start sending'.format(msgid))
	dante.scheduler_q.enqueue_call(func=retrieve_and_send, args=(msgid,))

def arrange_job(msgid, schedule_time):
	now = datetime.datetime.now()
	if schedule_time:
		if schedule_time <= now:
			logger.info('Immediate message [{0}] start sending'.format(msgid))
			dante.immediate_q.enqueue_call(func=retrieve_and_send, args=(msgid,))
		else:
			logger.info('Adding message [{0}] into APScheduler Redis jobstore'.format(msgid))
			dante.scheduler.add_job(add_to_schedule_queue, 'date',  run_date=schedule_time, args=[msgid], jobstore='redis')
	else:
		logger.info('Immediate message [{0}] start sending'.format(msgid))
		dante.immediate_q.enqueue_call(func=retrieve_and_send, args=(msgid,))
